package com.hznu.jspFinal.controller;


import com.hznu.jspFinal.entity.User;
import com.hznu.jspFinal.myBeans.R;
import com.hznu.jspFinal.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;


@Api(description = "用户管理接口",value = "user")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * author: fyk
     * time: 12:46 2018/5/31
     * function: myFunction
     * 
     * @param user
     * @return
     */
    @ApiOperation(value = "创建用户")
    @PostMapping("/addOne")
    public R addOne(@RequestBody User user)
    {
        try
        {
            if(userService.findByUsername(user.getUsername())!=null)
            {
                return R.error("用户名已被使用");
            }
            userService.addOne(user);
            return R.ok();
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * author: fyk
     * time: 12:46 2018/5/31
     * function: myFunction
     * 
     * @param id
     * @return
     */
    @ApiOperation(value = "通过用户ID查找单个用户")
    @GetMapping("/findByUserId/{id}")
    public R findByUserId(@PathVariable Integer id)
    {
        try
        {
            return R.ok().put("data",userService.findByUserId(id));
        }catch(Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation(value = "通过用户名查找单个用户")
    @GetMapping("/findByUsername/{username}")
    public R findByUsername(@PathVariable String username)
    {
        return R.ok().put("data",userService.findByUsername(username));
    }

    @ApiOperation(value="返回所有用户列表")
    @GetMapping("/findAll")
    public R findAll()
    {
        return R.ok().put("data",userService.findAll());
    }

    @ApiOperation(value="按条件查询用户")
    @PostMapping("/findBatchByCondition")
    public R findBatchByCondition(@RequestBody User user)
    {
        return R.ok().put("data",userService.findBatchByCondition(user));
    }

    @ApiOperation(value="通过用户id更新用户信息")
    @PostMapping("/updateByUserId")
    public R updateUser(@RequestBody User user)
    {
        try {
            userService.update(user);
            return R.ok();
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    @GetMapping("/delete")
    public R deleteUser(@RequestParam Integer id)
    {
        try{
            userService.delete(id);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }


}
